package com.sts.jdbc.impl;

import com.sts.jdbc.JdbcOperation;
import com.sts.jdbc.model.ColumnInfo;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lsl
 * @since 2025年07月04日 11:39
 */
public class PostgresqlOperationImpl implements JdbcOperation {
    @Override
    public List<String> getAllSchema(Connection connection) {
        List<String> resultList = new ArrayList<>();
        try (Connection con = connection) {

            String catalog = con.getCatalog();
            DatabaseMetaData databaseMetaData = con.getMetaData();

            try (ResultSet resultSet = databaseMetaData.getSchemas(catalog, null)) {
                while (resultSet.next()) {
                    String schemaName = resultSet.getString("TABLE_SCHEM");
                    resultList.add(schemaName);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return resultList;
    }

    @Override
    public List<String> getAllTable(Connection connection, String schema) {
        List<String> tableList = new ArrayList<>();

        try (Connection con = connection) {

            String catalog = con.getCatalog();
            DatabaseMetaData databaseMetaData = con.getMetaData();

            try (ResultSet resultSet = databaseMetaData.getTables(
                    catalog,
                    schema,
                    null,
                    new String[]{"TABLE"})
            ) {
                while (resultSet.next()) {
                    String tableName = resultSet.getString("TABLE_NAME");
                    tableList.add(tableName);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return tableList;
    }

    @Override
    public Map<String, ColumnInfo> getTableAllPrimaryKeyColumn(Connection connection, String schema, String table) {
        Map<String, ColumnInfo> columnInfoModelMap = new LinkedHashMap<>();

        try (Connection con = connection) {
            DatabaseMetaData metaData = con.getMetaData();

            try (ResultSet resultSet = metaData.getPrimaryKeys(null, schema, table)) {
                while (resultSet.next()) {
                    String columnName = resultSet.getString("COLUMN_NAME");
                    short keySeq = resultSet.getShort("KEY_SEQ");
                    String pkName = resultSet.getString("PK_NAME");

                    columnInfoModelMap.put(columnName.toUpperCase(),
                            new ColumnInfo(columnName, keySeq, pkName)
                    );
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        return columnInfoModelMap;
    }
}
